package com.rem.concurrency.juc.my11Future;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * 异步回调 CompletableFuture
 * // 异步执行
 * // 成功回调
 * // 失败回调
 *
 * @author Rem
 * @date 2021-03-10
 */

public class Demo01 {

    public static void main(String[] args) throws ExecutionException, InterruptedException {


        method2();

    }

    /**
     * 没有返回值的异步回调
     *
     * @throws InterruptedException
     * @throws ExecutionException
     */
    private static void method1() throws InterruptedException, ExecutionException {
        CompletableFuture<Void> future = CompletableFuture.runAsync(new Thread(() -> {

            try {
                TimeUnit.SECONDS.sleep(3);
                System.out.println("异步调用····");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "A"));

        System.out.println("yes");

        System.out.println(future.get());
    }


    private static void method2() throws InterruptedException, ExecutionException {
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(
                () -> {
                    try {
                        TimeUnit.SECONDS.sleep(1);
                       // int i = 1000 / 0;
                        System.out.println("异步调用····");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    return 456;
                }
        );

        System.out.println("yes");


        future.whenComplete(
                (a, b) -> {
                    // 正常的返回结果
                    System.out.println("a：" + a);
                    // 错误信息
                    System.out.println("b：" + b);
                }).exceptionally(e -> {
            //处理异常信息
            System.err.println("error:" + e.getMessage());
            return 111;
        }).get();
    }
}
